#include "Bird.h"
#include "EcoSystem.h"
#include<iostream>
#include "Environment.h"
Bird::Bird(EcoSystem *eco_system) : Consumer(eco_system)
{
    set_alive();
    set_max_hp(7000);
    set_hp(get_max_hp() / 2);
    set_init_speed(10.0);
    set_speed(get_init_speed());
    shelter = NULL;

    set_life_span(LIFE_SPAN[get_species_id()] * (1 + max(min(0.2, EcoSystem::random_double() - 0.5), -0.2)));
}
Bird::~Bird() {}

const unsigned int Bird::get_species_id() const
{
    return BIRD_SPECIES_ID;
}



Gdiplus::Image *Bird::get_entity_image() const
{
    static Gdiplus::Image *img = Gdiplus::Image::FromFile(L".\\images\\bird_l.png");
    static Gdiplus::Image *img_r = Gdiplus::Image::FromFile(L".\\images\\bird_r.png");

    if ((get_position() - get_prev_position()).x < 0)
        return img;
    else
        return img_r;
}

Entity *Bird::new_entity() const
{
    return new Bird(eco_system);
}

void Bird::on_tick()
{
    Environment *ptr = eco_system->get_environment_instance();
    if (ptr->get_temperature() > 30.0 || ptr->get_temperature() < 5.0){
        set_hp(get_hp()*0.8);
    }

    set_age(get_age() + 1);

    if (get_age() > get_life_span())
        set_dead();

    set_hp(get_hp() - 0.4 * get_speed() * get_speed() / 2);
    multiply();


    if (!avoid_predator(get_init_speed()*1.5))
        if (!prey(get_init_speed()))
            random_motion(get_init_speed()*0.5);

    /*if (go_left())
        is_go_left = true;
    else
        is_go_left = false;*/

    

    if (ptr->get_brightness() < 0.3)
        set_speed(get_speed()*0.8);
    else if (ptr->get_brightness() < 0.1 || ptr->get_weather() == 4)
        set_speed(get_speed()*0.5);

    //while it's rainy, birds will fly to trees
    if (ptr->get_weather() == 2 ){
        avoid_wetted(get_speed()*1.2);
    }

}

int    Bird::get_cost_of_being_preyed() const
{
    return get_hp() * 0.15;
}
int    Bird::get_gain_after_being_preyed() const
{
    return get_hp() * 0.2;
}

void Bird::avoid_wetted(double speed)
{
    bool type[MAX_SPECIES_COUNT] = { 0 };
    type[TREE_SPECIES_ID] = true;
    if (shelter == NULL || !shelter->is_alive() || Vector2D::distance(get_position(), shelter->get_position()) > 300.0)
    {
        shelter = eco_system->find_entity(this, type);
    }
    if (shelter != NULL)//find tree
    {
        Vector2D shelter_position = shelter->get_position();
        Vector2D distance = shelter_position - this->get_position();
        if (distance.modulus() < 5)
            brownian_motion(get_speed()*0.3);
        else{
            Vector2D displacement = distance * (1.0 / distance.modulus())* speed;
            shelter_position = get_position() + displacement;
            this->set_position(shelter_position);
        }
    }
}

void Bird::on_flush_memory()
{
    if (shelter != NULL && !shelter->is_alive())
        shelter = NULL;
}



